import React, { useState, useEffect, useCallback } from 'react';
import {
    Modal,
    Form,
    Input,
    DatePicker,
    InputNumber,
    Button,
    message
} from 'antd';
import {
    SaveOutlined
} from '@ant-design/icons';
import { stepService } from '../../services/stepService';
import dayjs from 'dayjs';

const { TextArea } = Input;

const StepForm = ({ visible, onCancel, onSuccess, step, taskId, steps = [] }) => {
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);

    // 计算默认的顺序值 - 如果是新增步骤，默认为当前最大顺序号+1
    const getDefaultOrder = useCallback(() => {
        if (steps.length === 0) return 1;

        // 找出最大的顺序号
        const maxOrder = Math.max(...steps.map(s => s.orderNum || s.order || 0));
        return maxOrder + 1;
    }, [steps]);

    const resetForm = useCallback(() => {
        if (step) {
            // 编辑现有步骤
            form.setFieldsValue({
                ...step,
                // 转换后端字段到前端字段
                order: step.orderNum,
                dueDate: step.expectedEndDate ? dayjs(step.expectedEndDate) : null,
                // 确保加载 estimatedHours
                estimatedHours: step.estimatedHours || 0,
            });
        } else {
            // 新建步骤，设置默认值
            form.setFieldsValue({
                title: '',
                description: '',
                estimatedHours: 1,
                dueDate: null,
                order: getDefaultOrder(), // 使用计算的默认顺序
            });
        }
    }, [form, step, getDefaultOrder]);

    useEffect(() => {
        if (visible) {
            resetForm();
        }
    }, [visible, resetForm]);

    const handleSubmit = async (values) => {
        setLoading(true);
        try {
            const stepData = {
                ...values,
                // 字段名称转换
                expectedEndDate: values.dueDate ? values.dueDate.toISOString() : null,
                orderNum: values.order,
                // 确保保留 estimatedHours 字段
                estimatedHours: values.estimatedHours,
                // 设置默认状态
                isCompleted: step?.isCompleted || false,
                // 移除前端特有字段
                dueDate: undefined,
                order: undefined,
                status: undefined
            };

            console.info(stepData);
            let response;
            if (step) {
                response = await stepService.updateStep(step.id, stepData);
            } else {
                response = await stepService.createStep(taskId, stepData);
            }

            if (response.data.success) {
                message.success(response.data.message || (step ? '步骤更新成功' : '步骤创建成功'));
                onSuccess(response.data.data);
            } else {
                message.error(response.data.message || (step ? '更新步骤失败' : '创建步骤失败'));
            }
        } catch (error) {
            message.error(step ? '更新步骤失败' : '创建步骤失败');
            console.error('Error saving step:', error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <Modal
            title={step ? '编辑步骤' : '新建步骤'}
            open={visible}
            onCancel={onCancel}
            footer={null}
            width={600}
        >
            <Form
                form={form}
                layout="vertical"
                onFinish={handleSubmit}
            >
                <Form.Item
                    name="title"
                    label="步骤标题"
                    rules={[{ required: true, message: '请输入步骤标题' }]}
                >
                    <Input placeholder="请输入步骤标题" />
                </Form.Item>

                <Form.Item
                    name="description"
                    label="步骤描述"
                >
                    <TextArea rows={4} placeholder="请输入步骤描述" />
                </Form.Item>

                <Form.Item
                    name="estimatedHours"
                    label="预计工时（小时）"
                    rules={[{ required: true, message: '请输入预计工时' }]}
                >
                    <InputNumber
                        min={0.5}
                        step={0.5}
                        placeholder="请输入预计工时"
                        style={{ width: '100%' }}
                    />
                </Form.Item>

                <Form.Item
                    name="dueDate"
                    label="截止日期"
                >
                    <DatePicker
                        style={{ width: '100%' }}
                        placeholder="请选择截止日期"
                    />
                </Form.Item>

                {/* 隐藏执行顺序字段，自动处理 */}
                <Form.Item
                    name="order"
                    hidden={true}
                >
                    <InputNumber />
                </Form.Item>

                <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
                    <Button onClick={onCancel} style={{ marginRight: 8 }}>
                        取消
                    </Button>
                    <Button
                        type="primary"
                        htmlType="submit"
                        loading={loading}
                        icon={<SaveOutlined />}
                    >
                        {step ? '更新' : '创建'}
                    </Button>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default StepForm;
